package com.rongke.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.rongke.commons.JsonResp;
import com.rongke.enums.FlowTypeEnum;
import com.rongke.enums.OrderStatusEnum;
import com.rongke.enums.PayTypeEnum;
import com.rongke.model.*;
import com.rongke.redis.CacheUtil;
import com.rongke.service.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @BuyTogetherGoodsController
 * @拼团商品Controller
 * @version : Ver 1.0
 */
@RestController
@RequestMapping(value="/api/buyTogetherGoods")
@Transactional
@CrossOrigin(origins = "*", maxAge = 3600)
public class BuyTogetherGoodsController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private BuyTogetherGoodsService buyTogetherGoodsService;
    @Autowired
    private CacheUtil cacheUtil;
    @Autowired
    private MuserService muserService;
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private AccountService accountService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private FlowDetailService flowDetailService;
    @Autowired
    private BuyTogetherUserService buyTogetherUserService;
    /**
     * @添加拼团商品
     * @param buyTogetherGoods
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/add", method = RequestMethod.POST)
    public JsonResp addBuyTogetherGoods(@RequestBody List<BuyTogetherGoods> buyTogetherGoods){
        log.debug("添加拼团商品");
        buyTogetherGoodsService.insertBatch(buyTogetherGoods);
        return JsonResp.ok(buyTogetherGoods);
    }

    /**
     * @修改拼团商品
     * @param buyTogetherGoods
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/update", method = RequestMethod.POST)
    public JsonResp updateBuyTogetherGoods(@RequestBody BuyTogetherGoods buyTogetherGoods){
        log.debug("修改拼团商品");
        buyTogetherGoodsService.updateById(buyTogetherGoods);
        return JsonResp.ok(buyTogetherGoods);
    }
    /**
     * @根据id查找拼团商品
     * @param id
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/selectOne", method = RequestMethod.GET)
    public JsonResp selectBuyTogetherGoods(Long id){
        log.debug("查找拼团商品");
        BuyTogetherGoods buyTogetherGoods = buyTogetherGoodsService.selectById(id);
        return JsonResp.ok(buyTogetherGoods);
    }

    /**
     * @根据条件查找拼团商品
     * @param buyTogetherGoods
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/selectByCondition", method = RequestMethod.POST)
    public JsonResp selectBuyTogetherGoodsByCondition(@RequestBody BuyTogetherGoods buyTogetherGoods){
        log.debug("根据条件查找拼团商品");
        if(buyTogetherGoods==null)
            return JsonResp.toFail("参数不能为空");
        List<BuyTogetherGoods> buyTogetherGoodsList=buyTogetherGoodsService.selectByCondition(buyTogetherGoods);
        return JsonResp.ok(buyTogetherGoodsList);
    }

    /**
     * @获取正在进行的拼团列表
     * @param page
     * @return
     */
    @RequestMapping(value = "/selectGroupBuyingList",method = RequestMethod.GET)
    public JsonResp selectGroupBuyingList(Page page){
        log.debug("获取正在进行的拼团列表");
        EntityWrapper<BuyTogetherGoods> ew = new EntityWrapper<>();
        ew.eq("is_activity_on",true);
        Page<BuyTogetherGoods> groupBuyingPage=buyTogetherGoodsService.selectPage(page,ew);
        return JsonResp.ok(groupBuyingPage);
    }

    /**
     * @根据id查找拼团商品
     * @param id
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/selectById", method = RequestMethod.GET)
    public JsonResp selectTogetherGoods(Long id){
        log.debug("查找拼团商品");
        BuyTogetherGoods buyTogetherGoods = buyTogetherGoodsService.selectViaId(id);
        return JsonResp.ok(buyTogetherGoods);
    }


    /**
     * @分页查找拼团商品列表
     * @param page
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/selectPage", method = RequestMethod.GET)
    public JsonResp selectNewGoods(Page page){
        log.debug("分页查找新品首发商品\n");
        Map map=new HashMap();
        map.put("startIndex",(page.getCurrent()-1)*page.getSize());
        map.put("size",page.getSize());
        List<BuyTogetherGoods> goodsPage = buyTogetherGoodsService.selectTogGoodsList(map);
        int total=buyTogetherGoodsService.selectCount(null);
        page.setRecords(goodsPage);
        page.setTotal(total);
        return JsonResp.ok(page);
    }

    /**
     * @将商品从拼团商品中删除
     * @param id
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/deleteBugTogetherGoods", method = RequestMethod.GET)
    public JsonResp deleteBugTogetherGoods(Long id){
        log.debug("将商品从拼团商品中删除");
        EntityWrapper<BuyTogetherUser>  ew=new EntityWrapper<>();
        ew.eq("btg_id",id);
        ew.eq("is_activity_on",true);
        List<BuyTogetherUser> buyTogetherUserList=buyTogetherUserService.selectList(ew);
        Set<Long> muserIds=new HashSet<>();
        for (BuyTogetherUser btu:buyTogetherUserList ) {
            muserIds.add(btu.getMuserId());
        }
        if(!buyTogetherUserList.isEmpty()){
            //开始退款操作
            EntityWrapper<Orders> ewOrder=new EntityWrapper<>();
            ewOrder.eq("order_type",1);
            List<Integer> statusList=new ArrayList<>();
            statusList.add(OrderStatusEnum.WAIT_SHIP.getType());
            statusList.add(OrderStatusEnum.BUYTOGETHER.getType());
            ewOrder.in("order_status", statusList);
            ewOrder.in("muser_id",muserIds);
            List<Orders> ordersList=ordersService.selectList(ewOrder);
            for(int i=0,y=ordersList.size();i<y;i++){
                Orders orders=ordersList.get(i);
                String outTradeNo=orders.getOutTradeNo();
                EntityWrapper<Account> ewAcc=new EntityWrapper<>();
                ewAcc.eq("muser_id",orders.getMuserId());
                Account account=accountService.selectOne(ewAcc);
                BigDecimal cashPayPrice=orders.getCashPayPrice();
                if(orders.getPayType()== PayTypeEnum.WEIXIN.getType()){
                    ClassLoader classLoader=getClass().getClassLoader();
                    URL url = classLoader.getResource("apiclient_cert.p12");
                    String path=url.getFile();
                    String refund_fee=new BigDecimal(100).multiply(cashPayPrice).setScale(0,BigDecimal.ROUND_HALF_UP).toString();
                    Map<String, String>  refundMap=ordersService.wxRefund(outTradeNo,refund_fee,refund_fee,path);
//                    Map<String, String>  refundMap= RefundUtil.wechatRefund(outTradeNo,refund_fee,refund_fee,path);
                    if(refundMap.containsKey("err_code")){
                        return JsonResp.fa(refundMap.get("err_code_des"));
                    }else if("FAIL".equals(refundMap.get("return_code"))){
                        return JsonResp.fa(refundMap.get("return_msg"));
                    }
                    /******************退款记录*************************/
                    FlowDetail fd=new FlowDetail();
                    fd.setMuserId(orders.getMuserId());
                    fd.setMoney(orders.getCashPayPrice());
                    fd.setFlowType(FlowTypeEnum.FEFUNDDUOBI.getType());
                    fd.setTitle("拼团失败微信退款金额"+orders.getCashPayPrice());
                    fd.setGmtDatetime(new Date());
                    flowDetailService.insert(fd);
                    if(orders.getCashPayPrice().compareTo(orders.getTotalPrice())<0){
                        Integer allowPayType=orders.getAllowPayType();
                        FlowDetail yue=new FlowDetail();
                        yue.setMuserId(orders.getMuserId());
                        yue.setMoney(orders.getTotalPrice().subtract(orders.getCashPayPrice()));
                        yue.setFlowType(FlowTypeEnum.FEFUNDDUOBI.getType());
                        BigDecimal leftMoney=orders.getTotalPrice().subtract(orders.getCashPayPrice());
                        if(allowPayType==1){
                            account.setDuoBi(account.getDuoBi().add(leftMoney));
                            yue.setTitle("拼团失败退款哆币金额"+leftMoney);
                        }else if(allowPayType==2){
                            account.setYaBi(account.getYaBi().add(leftMoney));
                            yue.setTitle("拼团失败退款雅币金额"+leftMoney);
                        }
                        yue.setGmtDatetime(new Date());
                        flowDetailService.insert(fd);
                    }
                }else if(orders.getPayType()== PayTypeEnum.ZHIFUBAO.getType()){
                    String strResponse=ordersService.alipayRefund(outTradeNo,"",cashPayPrice.doubleValue());
//                    String strResponse=  AlipayRefundUtil.alipayRefundRequest(outTradeNo,"",orders.getCashPayPrice().doubleValue());
                    if(strResponse!=null){
                        return JsonResp.fa(strResponse);
                    }
                    /******************退款记录*************************/
                    FlowDetail fd=new FlowDetail();
                    fd.setMuserId(orders.getMuserId());
                    fd.setMoney(orders.getCashPayPrice());
                    fd.setFlowType(FlowTypeEnum.FEFUNDDUOBI.getType());
                    fd.setTitle("拼团失败支付宝退款金额"+orders.getCashPayPrice());
                    fd.setGmtDatetime(new Date());
                    flowDetailService.insert(fd);
                    BigDecimal leftMoney=orders.getTotalPrice().subtract(orders.getCashPayPrice());
                    if(orders.getCashPayPrice().compareTo(orders.getTotalPrice())<0){
                        FlowDetail yue=new FlowDetail();
                        yue.setMuserId(orders.getMuserId());
                        yue.setMoney(orders.getTotalPrice().subtract(orders.getCashPayPrice()));
                        yue.setFlowType(FlowTypeEnum.FEFUNDDUOBI.getType());
                        if(orders.getAllowPayType()==1){
                            account.setDuoBi(account.getDuoBi().add(leftMoney));
                            yue.setTitle("拼团失败退款哆币金额"+leftMoney);
                        }else if(orders.getAllowPayType()==2){
                            account.setYaBi(account.getYaBi().add(leftMoney));
                            yue.setTitle("拼团失败退款雅币金额"+leftMoney);
                        }
                        yue.setGmtDatetime(new Date());
                        flowDetailService.insert(fd);
                    }
                }else{
                    if(orders.getPayType()== PayTypeEnum.DUOBI.getType()) {
                        account.setDuoBi(account.getDuoBi().add(orders.getTotalPrice()));
                    }else if(orders.getPayType()== PayTypeEnum.YABI.getType()){
                        account.setYaBi(account.getYaBi().add(orders.getTotalPrice()));
                    }
                    accountService.updateById(account);
                    /******************退款记录*************************/
                    FlowDetail fd=new FlowDetail();
                    fd.setMuserId(orders.getMuserId());
                    fd.setMoney(orders.getTotalPrice());
                    if(orders.getPayType()== PayTypeEnum.DUOBI.getType()) {
                        fd.setFlowType(FlowTypeEnum.FEFUNDDUOBI.getType());
                        fd.setTitle("拼团结束退还哆币金额"+orders.getTotalPrice());
                    }else if(orders.getPayType()== PayTypeEnum.YABI.getType()){
                        fd.setFlowType(FlowTypeEnum.FEFUNDYABI.getType());
                        fd.setTitle("拼团结束退还雅币金额"+orders.getTotalPrice());
                    }
                    fd.setUptDatetime(new Date());
                    flowDetailService.insert(fd);
                }
            }

        }

        buyTogetherGoodsService.deleteById(id);
        return JsonResp.ok();
    }


    /**
     * @分页查找拼团商品列表
     * @param page
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/selectTopGoods", method = RequestMethod.GET)
    public JsonResp selectTopGoods(Page page){
        log.debug("分页查找拼团商品");
        Map map=new HashMap();
        map.put("startIndex",(page.getCurrent()-1)*page.getSize());
        map.put("size",page.getSize());
        List<BuyTogetherGoods> goodsPage = buyTogetherGoodsService.selectTogGoodsList(map);
        int total=buyTogetherGoodsService.selectCount(null);
        page.setRecords(goodsPage);
        page.setTotal(total);
        return JsonResp.ok(page);
    }


    /**
     * @拼团成功
     * @param
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/BuyTogetherSuccess", method = RequestMethod.GET)
    public JsonResp BuyTogetherSuccess(String token,String buyTogetherCode) {
        log.debug("拼团成功");
        if(!cacheUtil.hasKey(token)){
            return JsonResp.fa(muserService.LOGINSTR);
        }
        Map btuM = new HashMap();
        btuM.put("buyTogetherCode", buyTogetherCode);
        List<BuyTogetherUser> btuList = buyTogetherUserService.selectBuyTogetherUser(btuM);
        Long btgId = btuList.get(0).getBtgId();
        //开团时间
        Date startTime=btuList.get(0).getBuyTogetherTime();
        Map map = new HashMap();
        map.put("btgId", btgId);
        BuyTogetherGoods buyTogetherGoods = buyTogetherGoodsService.selectTogetherGoods(map);
        buyTogetherGoods.setBtuList(btuList);

        Map btuMap = new HashMap();
        btuMap.put("btg", buyTogetherGoods);
        Long leftTime = startTime.getTime()+buyTogetherGoods.getBuyTogetherLimitTime()*60*60*1000-new Date().getTime();
        btuMap.put("leftTime", new SimpleDateFormat("HH:mm:ss").format(leftTime));
        return JsonResp.ok(btuMap);
    }

    /**
     * 根据产品线获取商品列表
     * @param goodsType
     * @return
     */
    @RequestMapping(value = "/getNotGroupedGoodsList",method = RequestMethod.GET)
    public JsonResp getNotGroupedGoodsList(int goodsType){
        log.debug("获取某产品线下未分组的商品集合");
        EntityWrapper<Goods> ew=new EntityWrapper<>();
        //goods_status 商品状态 1代表只上传未发布 2代表正式发布上架 3 下架
        ew.eq("goods_status",2).eq("goods_type",goodsType);
        List<Goods> goodsList=goodsService.selectList(ew);
        //查询已有的商品
        List<BuyTogetherGoods> btgList=buyTogetherGoodsService.selectTogGoodsList(new HashMap());
        if(!btgList.isEmpty()){
            for(int i=0,y=btgList.size();i<y;i++){
                Goods goods=btgList.get(i).getGoods();
                if(goodsList.contains(goods)){
                    goodsList.remove(goods);
                }
            }
        }

        return JsonResp.ok(goodsList);
    }
    /**
     * @批量添加
     * @param buyTogetherGoods
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/addBatch", method = RequestMethod.POST)
    public JsonResp addBatch(@RequestBody List<BuyTogetherGoods> buyTogetherGoods ){
        log.debug("批量添加");
        //buyTogetherGoodsService.insertBatch(buyTogetherGoods);
        return JsonResp.ok("");
    }
}
